import { Factory } from "./class/factory";
import { FactoryInfo } from "./class/factoryInfo";
import { getFactoryKey } from "./getFactoryKey";
import { getVersion } from "@/utils/version";

function get(key : string) : string | null {
	return localStorage.getItem(key);
}

function save(key : string, value : any) : void {
	localStorage.setItem(key, value);
}

function remove(key : string) {
	localStorage.removeItem(key);
}

function saveFactorys(list : Array<FactoryInfo>) {
	save("f-list-" + getVersion(), JSON.stringify(list));
}

function saveFactory(factory : Factory) {
	save(getFactoryKey(factory.id), JSON.stringify(factory));
}

/**
 * 根据版本号加载工厂列表
 * @return 该版本对应的工厂类
 */
export function loadFactorys() : Array<FactoryInfo> {
	var str = get("f-list-" + getVersion()); // 获取工厂列表字符串
	if (str == null) return [];
	else return JSON.parse(str);
}

/**
 * 根据工厂id获取工厂详细信息
 * @param {string} id 工厂id
 * @return 工厂详细信息
 */
export function openFactory(id : string) : Factory | null {
	let str = get(getFactoryKey(id));
	if (str == null) return null;
	else return JSON.parse(str);
}

/**
 * 创建工厂类
 * @return 新建的工厂
 */
export function createFactory() : Factory {
	let info : FactoryInfo = new FactoryInfo("未知工厂", "", "");
	let factory : Factory = new Factory(info.id, [], [], []);
	let list = loadFactorys();
	list.push(info);
	saveFactorys(list);
	saveFactory(factory);
	return factory;
}

/**
 * 保存工厂信息
 * @param {Factory} factory 工厂类
 * @return 无
 */
export function storeFactory(factory : Factory) : void {
	saveFactory(factory);
}

/**
 * 删除工厂
 * @param {string} id 工厂id
 * @return 删除结果
 */
export function removeFactory(id : string) : void {
	let list = loadFactorys(); // 加载工厂列表
	list = list.filter((f : FactoryInfo) => f.id != id); // 删除该工厂
	saveFactorys(list);
	remove(getFactoryKey(id));
}

/**
 * 保存工厂简略信息
 * @param {FactoryInfo} info 
 * @return 
 */
export function saveFactoryInfo(info : FactoryInfo) {
	let infos = loadFactorys();
	for (var i in infos) {
		if (infos[i].id == info.id) {
			infos[i] = info;
			break;
		}
	}
	saveFactorys(infos);
}

/**
 * 复制工厂
 * @param {string} id 工厂id
 * @return 复制的工厂
 */
export function copyFactory(id : string) : Factory | null {
	let factory : Factory | null = openFactory(id);
	let list = loadFactorys();
	let info : FactoryInfo | undefined = list.find((i) => i.id == id);
	if (factory == null || info == undefined) {
		alert("该工厂不存在");
		return null;
	}
	let newInfo : FactoryInfo = new FactoryInfo(info.name + "-copy", info.iconType, info.iconUrl);
	let newFactory : Factory = new Factory(newInfo.id, factory.recipes, factory.ingredients, factory.products);
	list.push(newInfo);
	saveFactorys(list);
	saveFactory(newFactory);
	return newFactory;
}